package com.ruoyi.questionBank.service.impl;

import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.questionBank.domain.QuestionBank;
import com.ruoyi.questionBank.mapper.QuestionBankMapper;
import com.ruoyi.questionBank.service.IQuestionBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class QuestionBankServiceImpl implements IQuestionBankService {
    @Autowired
    private QuestionBankMapper bankMapper;
    @Autowired
    private RedisCache cache;

    @Override
    public QuestionBank getBank() {
        QuestionBank bank = bankMapper.getQuestionBank();
        if(bank == null){
            if(cache.tryLock("question:bank:add" ,3000)) {
                try {
                    bank = bankMapper.getQuestionBank();
                    if(bank == null) {
                        bank = QuestionBank.build();
                        bankMapper.addQuestionBank(bank);
                    }
                }finally {
                    cache.unlock("question:bank:add");
                }
            }
        }
        return bank;
    }

    @Override
    public void updateQuestionBank(QuestionBank bank) {
        if(bank.getId() == null){
            throw new IllegalArgumentException("id cannot be null");
        }
        bankMapper.updateQuestionBank(bank);
    }

    @Override
    public void updateQuEnable() {
        QuestionBank bank = getBank();
        bank.setQuEnable(System.currentTimeMillis());
        updateQuestionBank(bank);
    }

    @Override
    public void updateQuUpdate() {
        QuestionBank bank = getBank();
        bank.setQuUpdate(System.currentTimeMillis());
        updateQuestionBank(bank);
    }

    @Override
    public void updateQuInsert() {
        QuestionBank bank = getBank();
        bank.setQuInsert(System.currentTimeMillis());
        updateQuestionBank(bank);
    }

    @Override
    public void updateQuDel() {
        QuestionBank bank = getBank();
        bank.setQuDel(System.currentTimeMillis());
        updateQuestionBank(bank);
    }
}
